package com.meiji.toutiao.module.news.article;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.meiji.toutiao.ErrorAction;
import com.meiji.toutiao.api.IMobileNewsApi;
import com.meiji.toutiao.bean.news.MultiNewsArticleBean;
import com.meiji.toutiao.bean.news.MultiNewsArticleDataBean;
import com.meiji.toutiao.util.RetrofitFactory;
import com.meiji.toutiao.util.TimeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Meiji on 2017/5/18.
 * 功能：新闻界面mvp中的  P
 */

public class NewsArticlePresenter implements INewsArticle.Presenter {

	private static final String TAG = "NewsArticlePresenter";
	private INewsArticle.View view;   // 接口
	private List<MultiNewsArticleDataBean> dataList = new ArrayList<>();  //  存放新闻数据结构对象的list
	private String category;
	private String time;          // 秒
	private Gson gson = new Gson();   // Gson解析数据的方法。
	private Random random = new Random();   // 随机对象

	/**
	 * 构造函数：参数：匿名实现接口的view
	 *
	 * @param view
	 */
	public NewsArticlePresenter(INewsArticle.View view) {
		this.view = view;
		this.time = TimeUtil.getCurrentTimeStamp();
	}

//    private int getRandom() {
//        if (this.time != 0) {
//            Random random = new Random();
//            StringBuilder result = new StringBuilder();
//            for (int i = 0; i < 6; i++) {
//                result.append(random.nextInt(10));
//            }
//            return this.time - Integer.parseInt(result.toString());
//        }
//        return 0;
//    }

	@Override  // 重写的方法：请求数据
	public void doLoadData(String... category) {

		try {
			if (this.category == null) {
				this.category = category[0];
			}
		} catch (Exception e) {
			ErrorAction.print(e);
		}

		// 释放内存
		if (dataList.size() > 150) {
			dataList.clear();
		}

//        Observable<MultiNewsArticleBean> ob1 = RetrofitFactory.getRetrofit().create(IMobileNewsApi.class)
//                .getNewsArticle(this.category, this.time);
//        Observable<MultiNewsArticleBean> ob2 = RetrofitFactory.getRetrofit().create(IMobileNewsApi.class)
//                .getNewsArticle2(this.category, this.time);

//        Observable.merge(ob1, ob2)

		// 这里是真正的网络请求，使用rxjava
		/*
		 *MultiNewsArticleBean ：网络获取的数据
		 * MultiNewsArticleDataBean :网络获取到的数据中content对象
		 * */
		getRandom()
				.subscribeOn(Schedulers.io())
				.switchMap(new Function<MultiNewsArticleBean, Observable<MultiNewsArticleDataBean>>() {
					@Override
					public Observable<MultiNewsArticleDataBean> apply(MultiNewsArticleBean multiNewsArticleBean) throws Exception {
						List<MultiNewsArticleDataBean> dataList = new ArrayList<>();
						for (MultiNewsArticleBean.DataBean dataBean : multiNewsArticleBean.getData()) {
							dataList.add(gson.fromJson(dataBean.getContent(), MultiNewsArticleDataBean.class));
						}
						return Observable.fromIterable(dataList);  // fromIterable接受可变长度的list，将数据发射出去
					}
				})
				.filter(new Predicate<MultiNewsArticleDataBean>() {
					@Override
					public boolean test(MultiNewsArticleDataBean dataBean) throws Exception {
						time = dataBean.getBehot_time();  // 从数据中拿去到时间秒
						if (TextUtils.isEmpty(dataBean.getSource())) {
							return false;
						}
						try {
							// 过滤头条问答新闻
							if (dataBean.getSource().contains("头条问答")
									|| dataBean.getTag().contains("ad")
									|| dataBean.getSource().contains("悟空问答")) {
								return false;
							}
							// 过滤头条问答新闻
							if (dataBean.getRead_count() == 0 || TextUtils.isEmpty(dataBean.getMedia_name())) {
								String title = dataBean.getTitle();
								if (title.lastIndexOf("？") == title.length() - 1) {
									return false;
								}
							}
						} catch (NullPointerException e) {
							ErrorAction.print(e);
						}
						// 过滤重复新闻(与上次刷新的数据比较)
						for (MultiNewsArticleDataBean bean : dataList) {
							if (bean.getTitle().equals(dataBean.getTitle())) {
								return false;
							}
						}
						return true;
					}
				})
				.toList()
				.map(new Function<List<MultiNewsArticleDataBean>, List<MultiNewsArticleDataBean>>() {
					@Override
					public List<MultiNewsArticleDataBean> apply(List<MultiNewsArticleDataBean> list) throws Exception {
						// 过滤重复新闻(与本次刷新的数据比较,因为使用了2个请求,数据会有重复)
						for (int i = 0; i < list.size() - 1; i++) {
							for (int j = list.size() - 1; j > i; j--) {
								if (list.get(j).getTitle().equals(list.get(i).getTitle())) {
									list.remove(j);
								}
							}
						}
						return list;
					}
				})
				.observeOn(AndroidSchedulers.mainThread())
				.as(view.bindAutoDispose())     // 解决内存泄露的问题
				.subscribe(new Consumer<List<MultiNewsArticleDataBean>>() {
					@Override
					public void accept(List<MultiNewsArticleDataBean> list) throws Exception {
						if (null != list && list.size() > 0) {
							NewsArticlePresenter.this.doSetAdapter(list);   // 由于这个接口方法被奔类重写了，所以将接收到的数据处理后，发送到重写方法中国
						} else {
							NewsArticlePresenter.this.doShowNoMore();  // 没有更多数据了
						}
					}
				}, new Consumer<Throwable>() {
					@Override
					public void accept(Throwable throwable) throws Exception {
						NewsArticlePresenter.this.doShowNetError();
						ErrorAction.print(throwable);
					}
				});
	}

	@Override  // 重写方法：再次加载数据
	public void doLoadMoreData() {
		doLoadData();
	}

	@Override // 重写方法：设置适配器。
	public void doSetAdapter(List<MultiNewsArticleDataBean> list) {
		dataList.addAll(list);       // 设置获取的数据。
		view.onSetAdapter(dataList);  // 在这个方法中调用View中ViewsetAdapter（）方法，将数据传递过去。
		view.onHideLoading();  // 同时调用view 方法，隐藏正在加载的加载提示框。
	}

	@Override  // 重写方法，这里是使用的INewsArtricle.Presenter的父接口IBasePresenter的方法 ---刷新
	public void doRefresh() {
		if (dataList.size() != 0) {
			dataList.clear();
			time = TimeUtil.getCurrentTimeStamp();
		}
		view.onShowLoading();
		doLoadData();
	}

	@Override  // 重写方法，这里是使用的INewsArtricle.Presenter的父接口IBasePresenter的方法  ---网路加载错误
	public void doShowNetError() {
		view.onHideLoading();     // 调用view中重写的隐藏加载
		view.onShowNetError();    // 显示网络错误
	}

	@Override  // 重写方法，加载完毕
	public void doShowNoMore() {
		view.onHideLoading();
		view.onShowNoMore();
	}

	/**
	 * 功能：是
	 *
	 * @return Observable对象
	 */
	private Observable<MultiNewsArticleBean> getRandom() {

		int i = random.nextInt(10);
		if (i % 2 == 0) {
			Observable<MultiNewsArticleBean> ob1 = RetrofitFactory.getRetrofit().create(IMobileNewsApi.class)
					.getNewsArticle(this.category, this.time);
			return ob1;
		} else {
			Observable<MultiNewsArticleBean> ob2 = RetrofitFactory.getRetrofit().create(IMobileNewsApi.class)
					.getNewsArticle2(this.category, this.time);
			return ob2;
		}
	}
}
